<template>
    <div>
        <a-page-header :title="blogtitle" @back="router.go(-1)">
        </a-page-header>
    </div>
    <div class="page4">
        <a-form ref="formref" :model="form" layout="vertical" >
        <a-form-item field="title" label="标题" :rules="[{required:true,message:'请输入标题'}]" >
      <a-input
        v-model="form.title"
        placeholder="请输入标题"
      />
    </a-form-item>
    <a-form-item field="summary" label="摘要" :rules="[{required:true,message:'请输入摘要'}]" >
      <a-input
        v-model="form.summary"
        placeholder="请输入摘要"
      />
    </a-form-item>
    <a-form-item field="content" label="内容" >
        <MdEditor v-model="form.content" @onSave="onSave" />
    </a-form-item>
   
    </a-form>
    </div>
</template>

<script setup>
import { ref } from 'vue';
import { useRouter } from 'vue-router';
import { MdEditor } from 'md-editor-v3';
import 'md-editor-v3/lib/style.css';
import { CREATE_BLOG,PUTBLOG,DESCRIBEBLOG } from '../../../api/blog';
import { Message } from '@arco-design/web-vue';
import { onBeforeMount } from 'vue';

const router = useRouter()
const form = ref({
    id:0,
    title:'',
    summary:'',
    content:''
})
const formref = ref(null)
const onSave = async()=> {
    // 校验表单
    const validate = await formref.value.validate()
    console.log(validate)
    // 保存表单
    if (validate === undefined) {
        console.log(validate)
        if (form.value.id === 0 ) {
            try {
            const resp =  await CREATE_BLOG(form.value)
            // console.log(resp)
            form.value = resp 
            console.log(form.value)
            Message.success('保存成功')
            } catch (error) {
                Message.error(`保存失败: ${error}`)
        }
        }else{
            try {
                const resp = await PUTBLOG(form.value.id,form.value)
                form.value = resp 
                Message.success('保存成功')
            } catch (error) {
                Message.error(`保存失败: ${error}`)
            }
        }
       
    } 
}
const blogtitle = ref("创建文章")
// 编辑逻辑
const filleditblog = async()=>{
    const id = router.currentRoute.value.query.id 
    if (id) {
        blogtitle.value = '更新文章'
        try {
        // 获取传入的id
        const  resp = await DESCRIBEBLOG(id)
        form.value = resp 
    } catch (error) {
        Message.error(`编辑失败: ${error}`)
    }
    }
    
}

onBeforeMount( ()=>{
    filleditblog()
})
</script>

<style lang="css" scoped>
.arco-page-header-back-btn{
    margin-right: 5px;
}
.arco-page-header-title{
    font-size: 15px;
}
.page4{
    margin-left: 20px;
}
</style>